package a66weding.com.jiehuntong.activity.home.hotel.shop;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewHeader;
import com.andview.refreshview.XScrollView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HomeBotomListBean;
import a66weding.com.jiehuntong.beans.HomeProductDetail;
import a66weding.com.jiehuntong.beans.HomeProductGuessLike;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.inner.ToNextInnner;
import a66weding.com.jiehuntong.widgets.MyListView;
import a66weding.com.jiehuntong.widgets.NoScrollGridView;

/**
 * 作用：商品详情，图文页页面
 * Created by admin on 2016/9/13.
 */
public class ShopTuWenFragment extends Fragment implements OnNetResultListener{
    private ToNextInnner innner;
    //产品id;
    private int producti_id;
    private TuWenGridAdapter gridAdapter;
    public void setInnner(ToNextInnner innner) {
        this.innner = innner;
    }
    //温馨提示;
    private TextView tv_notice;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getContext(), R.layout.fragment_shoptuwenfragment,null);
        tv_notice = (TextView) view.findViewById(R.id.tv_notice);
        initRefreshView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        producti_id =((HomeProductdetailActivity)getActivity()).getProducti_id();
        PCategory = ((HomeProductdetailActivity)getActivity()).getI_category();
        getDataFromServer();
        page = 1;
        getGridNet(page);
    }
    private XRefreshView xRefreshView;
    private MyListView list;
    private boolean isDownRefresh = true;
    private  TuwenAdapter adapter;
    private int page=1;
    private NoScrollGridView fragment_shop_tuwen_grid;
    private  int PCategory;
    private void initRefreshView(View view) {
        xRefreshView = (XRefreshView) view.findViewById(R.id.help_xrefreshview);
        // 设置是否可以上拉加载
        xRefreshView.setPullLoadEnable(true);
        // 设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        // 设置支持自动刷新
        xRefreshView.setAutoLoadMore(true);
        //listView
        list = (MyListView) view.findViewById(R.id.fragment_shop_tuwen_list);
        //gridView;
        fragment_shop_tuwen_grid = (NoScrollGridView) view.findViewById(R.id.fragment_shop_tuwen_grid);
        adapter = new TuwenAdapter(getContext(),null);
        gridAdapter = new TuWenGridAdapter(getContext(),null);
        list.setAdapter(adapter);
        fragment_shop_tuwen_grid.setAdapter(gridAdapter);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isDownRefresh = true;
                innner.toNext();
                xRefreshView.stopRefresh();
            }
            @Override
            public void onLoadMore(boolean isSlience) {
                isDownRefresh = false;
                ++page;
                getGridNet(page);
            }
        });
    }
    /**
     * GET WeddingMobileApi/get_CasesProductListLike?Token={Token}&pageIndex={pageIndex}&PCategory={PCategory}
     * 案例详细页面 猜你喜欢
     */
    private void getGridNet(int page){
        String url = RequestCode.get_CasesProductListLike+"&pageIndex="+page+"&PCategory="+PCategory;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url,
                this, HomeProductGuessLike.class, RequestCode.get_CasesProductListLike);
        HttpHandleUtil.executeCommonGet(getContext(),httpRequestBean);
    }
    /**
     * listVeiew;
     */
    private void getDataFromServer() {
        String url;
        if (((HomeProductdetailActivity)getActivity()).isLogin()) {
            url= RequestCode.get_ProductDetail+"&productId="+producti_id+"&memberID="+
                    DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        } else {
            url= RequestCode.get_ProductDetail+"&productId="+producti_id+"&memberID="+ 0;
        }
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url,
                this, HomeProductDetail.class, RequestCode.get_ProductDetail);

        HttpHandleUtil.executeCommonGet(getContext(),httpRequestBean);
    }
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (isDownRefresh){
            xRefreshView.stopRefresh();
        }else{
            xRefreshView.stopLoadMore();
        }
        if (data instanceof  HomeBotomListBean){
            HomeBotomListBean databean = (HomeBotomListBean) data;
           switch (databean.getResCode()){
               case "0000":
                   break;
           }
        }
        if (data instanceof HomeProductGuessLike ){
            HomeProductGuessLike  databean  = (HomeProductGuessLike) data;
            switch (databean.getResCode()){
                case "0000":
                    if (isDownRefresh){
                        gridAdapter.clear();
                    }
                    gridAdapter.append(databean.getData());
                    break;
            }
        }
        if(data instanceof HomeProductDetail){
            HomeProductDetail databean = (HomeProductDetail) data;
            switch (databean.getResCode()){
                case "0000":
                    String nt_details = databean.getData().getNt_Details();
                    final String[] imgUrls = nt_details.split(",");
                    final List<String> urlList = new ArrayList<String>();
                    for (int i = 0 ;i<imgUrls.length;i++){
                        urlList.add(imgUrls[i]);
                    }
                    adapter.append(urlList);
                    break;
            }
        }
    }
    @Override
    public void onError(ErrorBean errorBean) {}
    @Subscribe
    public void onEventMainThread(MessageEvent event) {
       String result  = event.getNotic();
        tv_notice.setText("* " + result);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    public void onWindowFocusChanged(boolean hasFocus) {
        if(hasFocus){// 窗口获取焦点（需要判断窗口第一次获取焦点）
            int count = xRefreshView.getChildCount();
            if(count == 3){
                if(xRefreshView.getChildAt(0) instanceof XRefreshViewHeader){
                    XRefreshViewHeader headerView = (XRefreshViewHeader)xRefreshView.getChildAt(0);
                    headerView.setVisibility(View.GONE);
                }
            }
        }
    }
}
